<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad"
      @cell-click="pageto">
      <!-- <template slot="menuLeft">
        <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="selectionList.length > 1 ? false : true"
          plain @click="handleDelete">删 除
        </el-button>
      </template> -->
      <!-- 自定义操作列 -->
      <template #menu="{ row, index, size }">
        <el-button type="primary" :size="'mini'" icon="el-icon-edit" @click="rowEdit(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
        <el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
      </template>
      <!-- 单元格 -->
      <template slot-scope="{ row }" slot="href">
        <div class="cell-color">{{ row.href }}</div>
      </template>
    </avue-crud>


  </basic-container>
</template>

<script>
import { getAdList, getPlacementsList, addPlacementsItem, updatePlacementsItem, delPlacementsItem } from "./api/placements";

import { mapGetters } from "vuex";
import website from "@/config/website";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: 'button',
        height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项 提示语
        searchShow: true,
        searchMenuSpan: 6,
        border: false,

        index: true,
        indexLabel: '序号',
        searchBtnText: '提交',
        searchBtnIcon: '提交',
        emptyBtnText: '重置',
        emptyBtnIcon: '重置',
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: true,
        addBtnText: '添加',
        addBtnIcon: 'el-icon-plus',
        delBtn: false,
        labelWidth: 130,
        column: [
          {
            label: "标题",
            prop: "title",
            rules: [
              {
                required: true,
                message: "请填写标题",
                trigger: "blur",
              },
            ],
          },
          {
            label: "位置标识",
            prop: "mark",
            type: "select",
            props: {
              label: "name",
              value: "mark",
            },
            dicData: [],
            rules: [
              {
                required: true,
                message: "请选择位置标识",
                trigger: "change",
              },
            ],
          },
          {
            label: "图片",
            prop: "img",
            type: "upload",
            clearable: true,    //图片是否可被删除、替换
            loadText: '图片上传中，请稍等',
            listType: "picture-img",//这是单图
            action: "/admin/common/upload",
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            limit: 1,
            dataType: "string",
            accept: [".png", ".jpg", ".jpeg"],
            tip: '上传png、jpg、jpeg的图片',
            uploadAfter: (file, done) => {
              console.log(file, '图片');
              done();
            }
          },
          {
            label: "跳转地址",
            prop: "href",
          },
          {
            label: "排序值",
            prop: "sort",
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            dicData: [{
              label: '启用',
              value: 0
            }, {
              label: '禁用',
              value: 1
            }],
          },
        ],
      },
      data: [],
      userInfo: {}
    };
  },

  computed: {
    ...mapGetters(["permission"]),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  created() {
    const user = localStorage.getItem(website.key + "-user");
    if (user) this.userInfo = JSON.parse(user);

    // this.getTagTypeData()
  },
  mounted() {
    getAdList({
      page: 1,
      size: 99999
    }).then((res) => {
      const resData = res.data;
      console.log(resData);
      this.option.column[1].dicData = resData.pagination.list

      
    });
  },
  methods: {
    // 创建超链接，不会被拦截    
    createSuperLabel(url, id) {
      let a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("target", "_blank");
      a.setAttribute("id", id);
      // 防止反复添加      
      if (!document.getElementById(id)) {
        document.body.appendChild(a);
      }
      a.click();
    },
    pageto(row, column) {
      if (column.columnKey == "href") {
        let uri = row.href;
        let id = "new_a"
        this.createSuperLabel(uri, id)
      }

      // if (column.columnKey == "href") {
      //   window.location.href = row.href
      // }
    },
    rowEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    rowDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    rowSave(row, done, loading) {
      let param = { ...row }
      addPlacementsItem(param).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      let params = { ...row }
      params.image_id = row.id
      updatePlacementsItem(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delPlacementsItem({ image_id: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },


    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delPlacementsItem({ ids: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(page_cursor) {
      this.page.currentPage = page_cursor;
    },
    sizeChange(page_size) {
      this.page.pageSize = page_size;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      let param = {
        ...params,
        page: page.currentPage,
        size: page.pageSize,
      }
      getPlacementsList(param).then((res) => {
        console.log('广告列表：', res.data.pagination);
        const resData = res.data;
        this.page.total = resData.pagination.total || 0;
        this.data = resData.pagination.list || [];
        this.loading = false;
        this.selectionClear();
      });
    },


    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.cell-color {
  color: #409eff !important;
  cursor: pointer;
}
</style>